/**
 * Created by wry on 2015/2/12.
 */
'use strict';

angular.module('backofficeApp.topicManager.controllers', ['simditor']).
    controller('topicListCtrl', ['$scope', 'topicService', 'CommunityService', 'spectialTopicService', '$http', '$location', function ($scope, topicService, communityService, spectialTopicService, $http, $location) {

        $scope.$on('$viewContentLoaded', function () {
            $scope.communityLabelList = communityService.getAllCommunityService();
            $scope.message = '发布专题';
            $scope.communityIds = '';
        });

        KindEditor.ready(function (K) {
            window.kinEdit = K.create('#editor_id', {
                uploadJson: '/rest/v1.0/Systems/uploadImages'
            });
        });

        $scope.editor = '';

        $scope.clearEditor = function () {
            kinEdit.html('')
        };
        $scope.items = [];
        $scope.addFile = function () {
            $scope.items.push(new Date());
        };

        $scope.deleteFile = function (item, path) {
            $scope.items.remove(item);
            var array = path.split('\\');
            var name = array[array.length - 1];

            $scope.images.forEach(function (image) {
                if (image.name == name) {
                    $scope.images.remove(image);
                }
            })
        };
        $scope.images = new Array();


        $scope.selectFile = function (files) {
            for (var i = 0; i < $scope.images.length; i++) {
                var image = $scope.images[i];
                if (image != null && image.name == files[0].name) {
                    image.file = files[0];
                    return;
                }
            }
            var temp = {
                "name": files[0].name,
                "file": files[0]
            };
            $scope.images.push(temp);

        };

        $scope.uploadFile = function () {
            $scope.fd = new FormData();
            for (var i = 0; i < $scope.images.length; i++) {
                var name = 'image' + (i + 1);
                $scope.fd.append(name, $scope.images[i].file);
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/Systems/oldUploadImages', $scope.fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).success(function (data) {
                $scope.urls = new Array();
                if (data.data != null) {
                    data.data.forEach(function (url) {
                        $scope.urls.push(fastDfsHostIp + url);
                    })
                }
            }).error(function () {
                $scope.msg = 'error';
            });

            //topicService.uploadImages($scope.images);
        };

        $scope.selectImage = function (item, name) {

            for (var i = 0; i < $scope.images.length; i++) {
                var image = $scope.images[i];
                if (image != null && image.item == item) {
                    image.name = name;
                    return;
                }
            }
            var temp = {
                "item": item,
                "name": name
            };
            $scope.images.push(temp);
        };

        $scope.postTopic = function (topic) {
            if (topic.title == null || topic.title == '') {
                alert('请输入标题');
                return;
            }
            if (topic.imageURL == null || topic.imageURL == '') {
                alert('请输入壁纸');
                return;
            }
            if (kinEdit.isEmpty()) {
                alert('请输入内容');
                return;
            }

            if (topic.summary == null || topic.summary == '') {
                alert('请输入简介');
                return;
            }

            var html = kinEdit.html();

            var a = html.replace(/width=.[0-9]*\"/g, '');
            a = a.replace(/height=.[0-9]*\"/g, '');
            a = a.replace(/style=\".*px\;\"/g, 'style=\"display:block;width:100%;\"');
            a = a.replace(/\<img/g, '<img style=\"display:block;width:100%;\"');
            a = a.replace(/\<embed/g, '<embed style=\"display:block;width:100%;\"');

            console.log(topic);
            var temp = {
                "community": $scope.data,
                "desc": a,
                "title": topic.title,
                "imageURL": topic.imageURL,
                "summary": topic.summary,
                "shareIcon": topic.shareIcon
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/postSpecialTopic', temp, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/topic');
                alert('发布成功')
            }).error(function () {
                alert('发布失败')
            });

        };

        $scope.data = new Array();
        $scope.toggle = function (ck, objId) {
            if (ck == null && $scope.communityIds.indexOf(objId) != -1) {
                ck = true;
            }
            !ck ? $scope.data.push(objId) : $scope.data.remove(objId);
        };

        $scope.addTopic = function () {
            $location.path('/topicAdd');
        };

        $scope.generateAllTopicHtml = function () {
            spectialTopicService.get(function (res) {
                alert(res.result.message);
            })
        };

        var commId;

        $scope.getTopicList = function (communityId) {
            if (communityId == null) {
                communityId = '1';
                commId = '1'
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/getAllCommunityTopic/' + communityId + '/2', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.topicList = data.data;
            }).error(function () {
                $scope.topicList = null;
            });
        };

        $scope.getTopicList();

        $scope.deleteTopic = function (id) {

            bootbox.confirm('是否删除专题', function (result) {
                if (result == true) {
                    $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/deleteTopic/' + id, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.getTopicList(commId);
                    }).error(function () {
                    });
                }
            }).find("div.modal-dialog").css({width: '30%'});
        };

        $scope.editTopic = function (objId) {
            $location.path('/topicEdit/' + objId);
        };

        $scope.setTopicStatus = function (id, status) {
            var opt = {
                id: id,
                status: status
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/setTopicStatus', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getTopicList(commId);
            }).error(function () {
                $scope.getTopicList(commId);
            });
        };

        $scope.previewTopic = function (url) {

            var body = document.getElementById("qrBody");
            var div = document.getElementById("qrcodeCanvas");

            body.removeChild(div);

            var newMask = document.createElement("div");
            newMask.id = "qrcodeCanvas";
            body.appendChild(newMask);

            $('#qrDiv').modal('show');
            $('#qrcodeCanvas').qrcode(url);
        }
    }
    ]).controller('topicEditCtrl', ['$scope', '$routeParams', 'CommunityService', '$http', '$location', function ($scope, $routeParams, communityService, $http, $location) {

        KindEditor.ready(function (K) {
            window.kinEdit = K.create('#editor_id', {
                uploadJson: '/rest/v1.0/Systems/uploadImages'
            });
        });

        $scope.data = new Array();

        $scope.$on('$viewContentLoaded', function () {
            $scope.communityLabelList = communityService.getAllCommunityService();
            $scope.message = '更新专题';
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/getTopicById/' + $routeParams.objId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.topic = data.data;
                $scope.data = $scope.topic.community;
                $scope.communityIds = '';
                $scope.topic.community.forEach(function (temp) {
                    $scope.communityIds += temp;
                });
                kinEdit.html($scope.topic.desc)
            }).error(function () {
            });
        });

        $scope.toggle = function (ck, objId) {
            if (ck == null && $scope.communityIds.indexOf(objId) != -1) {
                ck = true;
            }
            !ck ? $scope.data.push(objId) : $scope.data.remove(objId);
        };


        $scope.postTopic = function (topic) {
            if (topic.title == null || topic.title == '') {
                alert('请输入标题');
                return;
            }
            if (topic.imageURL == null || topic.imageURL == '') {
                alert('请输入壁纸');
                return;
            }
            if (kinEdit.isEmpty()) {
                alert('请输入内容');
                return;
            }

            if (topic.summary == null || topic.summary == '') {
                alert('请输入简介');
                return;
            }

            var html = kinEdit.html();

            var a = html.replace(/width=.[0-9]*\"/g, '');
            a = a.replace(/height=.[0-9]*\"/g, '');
            a = a.replace(/style=\".*px\;\"/g, 'style=\"display:block;width:100%;\"');
            a = a.replace(/\<img/g, '<img style=\"display:block;width:100%;\"');
            a = a.replace(/\<embed/g, '<embed style=\"display:block;width:100%;\"');

            var temp = {
                "community": $scope.data,
                "id": topic.objId,
                "desc": a,
                "title": topic.title,
                "imageURL": topic.imageURL,
                "summary": topic.summary
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/postSpecialTopic', temp, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/topic')
            }).error(function () {
                alert('更新成功')
            });

        };

    }]).controller('specialNewsCtrl', ['$scope', '$location', '$http', 'CommunityService', function ($scope, $location, $http, communityService) {

        $scope.communityLabelList = communityService.getAllCommunityService();


        var commId = '1';

        $scope.getFreshNewsList = function (communityId) {
            if (communityId == null) {
                communityId = '1'
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/getSpecialNewsList/' + communityId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.newsList = data.data;

            }).error(function () {
                $scope.newsList = null;
            });
        };

        $scope.getFreshNewsList(commId);


        $scope.data = new Array();
        $scope.toggle = function (ck, objId) {
            !ck ? $scope.data.push(objId) : $scope.data.remove(objId);
        };

        $scope.gotoSpecialNewsAddPage = function () {
            $location.path('/specialNews/add');
        };

        $scope.gotoSpecialNewsListPage = function () {
            $location.path('/specialNews');
        };

        $scope.createSpecialNews = function (news) {
            if (news.type == null || news.type == '') {
                return;
            }
            if (news.title == null || news.title == '') {
                return;
            }
            if (news.url == null || news.url == '') {
                return;
            }

            var temp = {
                "community": $scope.data,
                "type": news.type,
                "title": news.title,
                "url": news.url
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/createSpecialNews', temp, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/specialNews');
            }).error(function () {
            });
        };

        $scope.showSetting = false;
        $scope.settingMessage = '设置顺序';

        $scope.setOrder = function () {
            if ($scope.showSetting) {
                $scope.showSetting = false;
                $scope.settingMessage = '设置顺序'
                $scope.getFreshNewsList(commId);
            } else {
                $scope.showSetting = true;
                $scope.settingMessage = '取消设置'
            }
        };

        $scope.confirmOrder = function () {
            var newsIdList = new Array();
            $scope.newsList.forEach(function (news) {
                newsIdList.push(news.objId);
            });

            var temp = {
                "newsId": newsIdList
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/confirmOrder', temp, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.showSetting = false;
                $scope.settingMessage = '设置顺序'
                $scope.getFreshNewsList(commId);
            }).error(function () {

            });
        };

        $scope.removeNews = function (newsId) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/removeNews/' + newsId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getFreshNewsList(commId);
            }).error(function () {

            });
        };

        $scope.upNews = function (index) {
            if (index > 0) {
                var temp = $scope.newsList[index]
                $scope.newsList[index] = $scope.newsList[index - 1]
                $scope.newsList[index - 1] = temp;
            }
        };
        $scope.downNews = function (index) {
            if (index < $scope.newsList.length - 1) {
                var temp = $scope.newsList[index];
                $scope.newsList[index] = $scope.newsList[index + 1]
                $scope.newsList[index + 1] = temp;
            }
        }


    }]).controller('pushCtrl', ['$scope', '$location', '$http', 'CommunityService', 'MasterDataService', function ($scope, $location, $http, communityService, masterDataService) {

        $scope.hobbies = masterDataService.getAllDicService({category: '01'});

        var commId;

        $scope.table = 1;

        $scope.communityLabelList = communityService.getAllCommunityService();

        $scope.currentPage = 1;
        $scope.numPages = 10;
        $scope.pageSize = 10;
        $scope.pages = [];

        $scope.getQuestionList = function (communityId) {
            var opt = {};
            opt['isValid'] = true;

            if (communityId != null) {
                opt['community'] = communityId;
                commId = communityId
            } else {
                commId = null;
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/getRecommendQuestion/' + $scope.currentPage + '/' + $scope.pageSize, opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.questionList = data.data.questionList;
                $scope.numPages = data.data.totalPage;
            }).error(function () {
                $scope.questionList = null;
            });
        };

        $scope.getNoticeList = function (communityId) {
            if (communityId == null) {
                communityId = '1'
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/getAllCommunityNotice/' + communityId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.noticeList = data.data;

            }).error(function () {
                $scope.noticeList = null;
            });
        };

        $scope.getTopicList = function (communityId) {
            if (communityId == null) {
                communityId = '1'
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/getAllCommunityTopic/' + communityId + '/0', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.topicList = data.data;
            }).error(function () {
                $scope.topicList = null;
            });
        };

        $scope.getActivityList = function (communityId) {
            if (communityId == null) {
                communityId = '1'
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/getCommunityActivityList/' + communityId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.activityList = data.data;
            }).error(function () {
                $scope.activityList = null;
            });
        }

        $scope.getNeighbourActivityList = function (communityId) {
            if (communityId == null) {
                return;
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/getBackOfficeActivityList/' + communityId + '/' + $scope.currentPage + '/3', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                //$scope.totalPage = data.data.totalPage;
                $scope.neighbourActivityList = data.data.aList;

            }).error(function (data) {
            });
        };

        $scope.getAllList = function (communityId) {

            $scope.currentPage = 1;

            $scope.getNoticeList(communityId);
            $scope.getQuestionList(communityId);
            $scope.getTopicList(communityId);
            $scope.getActivityList(communityId);
            $scope.getNeighbourActivityList(communityId);
        };

        $scope.getAllList(commId);

        $scope.initCurrentPage = function (table) {
            $scope.currentPage = 1;
            $scope.table = table;

            $scope.onSelectPage(1);
        };

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;

            switch ($scope.table) {
                case 1:
                    $scope.getQuestionList(commId);
                    break;
                case 2:
                    $scope.getNeighbourActivityList(commId);
                    break;
                case 3:
                    break;
                case 4:
                    break;
            }
        };

        $scope.showPushMessage = function (title, message, type) {
            if ($scope.data == 7 && $scope.userId == null) {
                alert('请输入用户id');
                return;
            }
            if ($scope.data == 8 && $scope.hobbyName == null) {
                alert('请选择兴趣爱好');
                return;
            }
            if (title == null) {
                alert('请输入通知内容');
                return;
            }
            $scope.message = null;
            $('#showPushMessage').modal('toggle');

            if ($scope.data == 2) {                               //读取导入文件
                if (uList == null || uList.length < 2) {
                    alert('文件有错误');
                    return;
                }
                setMessage(uList, title, type, message);
            } else if ($scope.data == 3) {                         //不活跃用户
                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/getNotActiveUser/' + commId, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    setMessage(data.data, title, type, message);
                }).error(function () {

                });
            } else if ($scope.data == 7) {     //单人用户
                setMessage([$scope.userId], title, type, message);
            } else if ($scope.data == 8) {     //兴趣爱好
                var input = {
                    hobbyName: $scope.hobbyName,
                    community: commId
                };
                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/marketing/getUserListByHobby', input, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    setMessage(data.data, title, type, message);
                }).error(function () {
                    setMessage([], title, type, message);
                });
            } else {
                var opt = {};
                if ($scope.data == 1) {                //小区用户
                    opt = {
                        community: commId
                    }
                } else if ($scope.data == 4) {         //达人用户
                    opt = {
                        userType: 'talent',
                        community: commId
                    }
                } else if ($scope.data == 5) {         //V认证用户
                    opt = {
                        authenticationStatus: true,
                        community: commId
                    }
                } else if ($scope.data == 6) {
                    opt = {
                        authenticationStatus: false,   //未认证用户
                        community: commId
                    }
                }

                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/getPushUserList', opt, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    setMessage(data.data, title, type, message);
                }).error(function () {
                });

            }
        };

        var setMessage = function (uList, title, type, message) {
            if (type == 1) {
                $scope.message = {
                    tag: '话题',
                    content: message.desc,
                    uList: uList,
                    type: 1,
                    openType: 1,
                    contentId: message.objId,
                    createdBy: message.createdBy.objId,
                    desc: title
                }
            } else if (type == 2) {
                $scope.message = {
                    tag: '公告',
                    content: message.title,
                    uList: uList,
                    type: 1,
                    openType: 2,
                    contentId: message.objId,
                    desc: title
                }
            } else if (type == 3) {

                var opt = {
                    url: message.url
                };
                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/shortUrl', opt, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.message = {
                        tag: '专题',
                        content: message.title,
                        uList: uList,
                        type: 1,
                        url: data.data,
                        openType: 4,
                        contentId: message.objId,
                        desc: title
                    }
                }).error(function () {
                    $scope.message = {
                        tag: '专题',
                        content: message.title,
                        uList: uList,
                        type: 1,
                        url: message.url,
                        openType: 4,
                        contentId: message.objId,
                        desc: title
                    }
                });
            } else if (type == 4) {
                $scope.message = {
                    tag: '活动',
                    content: message.title,
                    uList: uList,
                    url: message.url,
                    type: 1,
                    openType: 3,
                    contentId: message.objId,
                    desc: title
                }
            } else if (type == 6) {
                $scope.message = {
                    tag: '邻里活动',
                    content: message.desc,
                    uList: uList,
                    type: 1,
                    openType: 6,
                    contentId: message.objId,
                    createdBy: message.createdBy.objId,
                    desc: title
                }
            }
        };


        $scope.confirmPush = function () {
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/confirmPush', $scope.message, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

            }).error(function () {

            });
        };

        var uList;

        $scope.handleFiles = function (files) {
            if (files.length) {
                var value;
                var file = files[0];
                var reader = new FileReader();
                reader.onload = function () {
                    value = this.result;
                    uList = value.split(',');
                };
                reader.readAsText(file);
            }
        }


    }]).directive('paging', function () {
        return {
            restrict: 'E',
            //scope: {
            //    numPages: '=',
            //    currentPage: '=',
            //    onSelectPage: '&'
            //},
            template: '',
            replace: true,
            link: function (scope, element, attrs) {

                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.numPages ? scope.numPages : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('numPages', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.numPages;
                };

            }
        };
    });

Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
